package com.gnerv.oauth.service;

import com.gnerv.oauth.dto.ClientDetailsDTO;
import com.gnerv.oauth.entity.Client;
import com.gnerv.oauth.entity.ClientDetails;
import com.gnerv.oauth.mapper.ClientDetailsMapper;
import com.gnerv.oauth.mapper.ClientMapper;
import com.gnerv.oauth.utils.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ClientService {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private ClientMapper clientMapper;
    @Resource
    private ClientDetailsMapper clientDetailsMapper;

    public boolean saveClient(ClientDetailsDTO clientDetailsDTO) {
        String clientId = UUIDUtils.getLower();

        clientDetailsDTO.setClientSecret(passwordEncoder.encode(clientDetailsDTO.getClientSecret()));
        Client client = new Client();
        client.setClientId(clientId);
        BeanUtils.copyProperties(clientDetailsDTO, client);
        clientMapper.insert(client);

        ClientDetails clientDetails = new ClientDetails();
        BeanUtils.copyProperties(clientDetailsDTO, clientDetails);
        clientDetails.setClientId(clientId);
        clientDetails.setResourceIds("");
        clientDetails.setScope("all");
        clientDetails.setAutoApprove("false");
        clientDetails.setAccessTokenValidity(300);
        clientDetails.setRefreshTokenValidity(1500);
        clientDetailsMapper.insert(clientDetails);
        return true;
    }
}
